<template>
  <div>
    <el-dialog
      title="编辑机器人"
      v-model="state.isShow"
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      align-center
      width="1000px"
      @closed="closed"
    >
      <div class="robot-dialog-box">
        <el-scrollbar always class="w-full h-full overflow-hidden box-border" ref="scrollbarRef">
          <div>
            <section class="add-item flex">
              <article><span>头像</span></article>
              <article>
                <avatar :size="30" :src="form.Avatar"></avatar>
                <system-img @update="handleSetAvatar">
                  <el-button class="mx-[10px]" type="primary" size="small">系统头像</el-button>
                </system-img>
                <upload-img @update="handleSetAvatar">
                  <el-button type="primary" size="small">上传头像</el-button>
                </upload-img>
              </article>
            </section>
            <div class="flex items-center">
              <section class="add-item flex flex-[1.5]">
                <article><span class="required">✲</span><span>机器人名称</span></article>
                <article>
                  <el-input readonly disabled v-model="form.Name" placeholder="请输入机器人名称" />
                </article>
              </section>
              <section class="add-item flex flex-1 ml-[4px]">
                <article class="!w-[100px]">
                  <span class="required">✲</span><span>机器人昵称</span>
                </article>
                <article>
                  <el-input v-model="form.Nickname" placeholder="请输入机器人名称" />
                </article>
              </section>
              <section class="add-item flex flex-1 ml-[4px]">
                <article class="!w-[100px]">状态</article>
                <article>
                  <el-switch
                    v-model="form.Status"
                    inline-prompt
                    size="large"
                    active-text="开启"
                    inactive-text="关闭"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </article>
              </section>
            </div>
            <div class="flex items-center">
              <section class="add-item flex flex-1">
                <article>
                  <el-tooltip effect="dark" placement="top">
                    <template #content>
                      <p>
                        <b>自动上分固定金额：</b>可以设置多个，用井号 #
                        分隔，自动上分金额最好不要大于自动下分警戒线。根据当前设定的自动上分积分，取一个金额去上分，上分后托积分大于上分警戒线。
                      </p>
                      <div>
                        <p>
                          <b>自动上分随机金额：</b>可以设置范围区间，用井号 #
                          分隔，自动上分随机金额范围最好不要大于自动下分警戒线。根据当前设定的自动上分随机金额，取随机金额范围内的10整倍去上分，上分后托积分大于上分警戒线。
                        </p>
                      </div>
                    </template>
                    <el-icon class="!text-[18px] mr-[5px]" color="#0086b3">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                  <el-select v-model="form.DepositType">
                    <el-option label="自动上分固定金额" :value="1" />
                    <el-option label="自动上分随机金额" :value="2" />
                  </el-select>
                </article>
                <article>
                  <el-input v-model="form.DepositAmount" placeholder="200#300#500#800#1000" />
                </article>
              </section>
              <section class="add-item flex flex-1 ml-[4px]">
                <article>
                  <el-tooltip effect="dark" placement="top">
                    <template #content>
                      <p>
                        <b>自动下分固定金额：</b>可以设置多个，用井号 #
                        分隔，自动下分金额最好不要大于自动上分警戒线。根据托当前积分，取一个金额去下分，下分后托积分小于下分警戒线且大于自动上分警戒线。
                      </p>
                      <div>
                        <p>
                          <b>自动下分随机金额：</b>可以设置范围区间，用井号 #
                          分隔，自动下分随机金额范围最好不要大于自动上分警戒线。根据当前设定的自动下分随机金额，取随机金额范围内的10整倍去下分，下分后托积分小于下分警戒线且大于自动上分警戒线
                        </p>
                      </div>
                    </template>
                    <el-icon class="!text-[18px] mr-[5px]" color="#0086b3">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                  <el-select v-model="form.WithdrawType">
                    <el-option label="自动下分固定金额" :value="1" />
                    <el-option label="自动下分随机金额" :value="2" />
                  </el-select>
                </article>
                <article>
                  <el-input v-model="form.WithdrawAmount" placeholder="200#300#500#800#1000" />
                </article>
              </section>
            </div>
            <div class="flex items-center">
              <section class="add-item flex flex-1">
                <article>
                  <el-tooltip content="托每一笔注单下注的最小金额" effect="dark" placement="top">
                    <el-icon class="!text-[18px] mr-[5px]" color="#0086b3">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                  <span>最小下注金额</span>
                </article>
                <article>
                  <el-input type="number" v-model="form.MiniBet" placeholder="请输入最小下注金额" />
                </article>
              </section>
              <section class="add-item flex flex-1 ml-[4px]">
                <article>
                  <el-tooltip
                    content="托每一笔注单下注的最大金额，最大下注金额最好不要大于自动上分警戒线"
                    effect="dark"
                    placement="top"
                  >
                    <el-icon class="!text-[18px] mr-[5px]" color="#0086b3">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                  <span>最大下注金额</span>
                </article>
                <article>
                  <el-input type="number" v-model="form.MaxBet" placeholder="请输入最大下注金额" />
                </article>
              </section>
            </div>
            <section class="add-item last-item flex">
              <article><span>下注游戏</span></article>
              <article>
                <div v-for="item in games" :key="item.LotteryId" class="game">
                  <span>{{ item.Name }}</span>
                  <el-switch
                    size="large"
                    v-model="item.Checked"
                    @change="handelSwitch(item.Checked!, item.LotteryId)"
                  />
                </div>
              </article>
            </section>
          </div>
        </el-scrollbar>
      </div>

      <template #footer>
        <el-button @click="closed">取 消</el-button>
        <el-button
          :disabled="state.updating"
          :loading="state.updating"
          type="primary"
          @click="confirm"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { message } from "@/utils/message";
import { cloneDeep, debounce } from "lodash-es";
import { storeToRefs } from "pinia";
import { useGameStore } from "~/store/modules/game";
import type { ElScrollbar } from "element-plus";
import { GameCategory } from "@/enums";
import { reqRobotEdit } from "@/api/user";

interface State {
  updating: boolean;
  isShow: boolean;
}

const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
const games = ref(gameTotal.value.filter(item => item.CategoryId !== GameCategory.lhc));

const props = withDefaults(
  defineProps<{
    data: RobotMo | null;
  }>(),
  {
    data: null
  }
);
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>();
const emit = defineEmits(["update"]);

const state = reactive<State>({
  updating: false,
  isShow: false
});
const defaultForm = {
  Name: "",
  Nickname: "",
  Avatar: "",
  Status: 1,
  DepositType: 1,
  WithdrawType: 1,
  DepositAmount: "200#300#500#800#1000#2000",
  WithdrawAmount: "200#300#500#800#1000#2000",
  MiniBet: "10",
  MaxBet: "200",
  BetGame: ""
};
const form = reactive({ ...defaultForm });

const closed = () => {
  state.isShow = false;
  Object.assign(form, defaultForm);
};

const open = () => {
  state.isShow = true;
  initGames();
};

const initGames = () => {
  if (!props.data) return;
  setTimeout(() => {
    scrollbarRef.value!.setScrollTop(0);
  }, 0);
  Object.assign(form, props.data);
  const betGame: string[] = props.data.BetGame.match(/\d+/g) || [];
  form.BetGame = betGame.length > 0 ? betGame.join(",") : "";
  games.value.forEach(item => {
    item.Checked = betGame.includes(String(item.LotteryId));
  });
};

const handelSwitch = (flag: boolean, id: number) => {
  let betGame = form.BetGame ? form.BetGame.split(",") : [];
  if (flag) {
    betGame.push(String(id));
  } else {
    betGame = betGame.filter(item => Number(item) !== id);
  }
  form.BetGame = betGame.length > 0 ? betGame.join(",") : "";
};

const handleSetAvatar = (img: string) => {
  form.Avatar = img;
};

function validateFormat(input: string) {
  const regex = /^(\d+#)+\d+$/;
  return regex.test(input);
}

const confirm = debounce(
  async () => {
    if (!form.Nickname) {
      return message.warning("请输入机器人昵称");
    }
    if (form.DepositAmount == "") {
      return message.warning("请输入自动上分金额");
    }
    if (!validateFormat(form.DepositAmount)) {
      return message.warning("请输入正确的自动上分金额");
    }
    if (form.WithdrawAmount == "") {
      return message.warning("请输入自动下分金额");
    }
    if (!validateFormat(form.WithdrawAmount)) {
      return message.warning("请输入正确的自动下分金额");
    }
    if (form.MiniBet == "") {
      return message.warning("请输入最小下注金额");
    }
    if (form.MaxBet == "") {
      return message.warning("请输入最大下注金额");
    }
    if (!form.BetGame) {
      return message.warning("请选择下注游戏");
    }
    try {
      state.updating = true;
      await reqRobotEdit({
        Id: props.data?.Id,
        ...form,
        DepositType: Number(form.DepositType),
        WithdrawType: Number(form.WithdrawType),
        MiniBet: Number(form.MiniBet),
        MaxBet: Number(form.MaxBet),
        BetGame: form.BetGame.split(",")
          .map(num => `{${num}}`)
          .join("")
      });
      state.updating = false;
      message.success("修改机器人成功");
      closed();
      emit("update");
    } catch (error) {
      state.updating = false;
      console.log(error);
    }
  },
  500,
  { leading: true, trailing: false }
);

watch(
  () => gameTotal.value,
  val => {
    games.value = cloneDeep(val.filter(item => item.CategoryId !== GameCategory.lhc));
  }
);

watch(
  () => form.DepositType,
  val => {
    if (val == 1) {
      form.DepositAmount = "200#300#500#800#1000#2000";
    } else {
      form.DepositAmount = "200#2000";
    }
  }
);

watch(
  () => form.WithdrawType,
  val => {
    if (val == 1) {
      form.WithdrawAmount = "200#300#500#800#1000#2000";
    } else {
      form.WithdrawAmount = "200#2000";
    }
  }
);

defineExpose({
  open
});
</script>
<style scoped lang="scss">
.add-item {
  border: 1px solid #ddd;
  justify-content: space-between;
  margin-bottom: 10px;
  overflow: hidden;
  border-radius: 6px 0 0 6px;
  article:first-child {
    width: 180px;
    padding: 0 15px;
    border-right: 1px solid #ddd;
    background-color: #e5f1f5;
    border-radius: 6px 0 0 6px;
    .required {
      margin-right: 2px;
    }
  }
  article:last-child {
    padding: 2px 6px;
    flex-grow: 1;
    width: 0;
    min-height: 36px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  article {
    display: flex;
    align-items: center;
  }
  .game {
    display: flex;
    align-items: center;
    width: 25%;
    margin-bottom: 5px;
    > span {
      width: 100px;
      margin-left: 5px;
      font-size: 13px;
    }
  }
  :deep() {
    .el-input,
    .el-textarea {
      --el-input-bg-color: #f9f9f9;
    }
    .el-input {
      width: 400px !important;
    }
    .el-select__selected-item {
      font-size: 14px;
    }
  }
}
.last-item {
  border-bottom: 1px solid #ddd;
}
.robot-dialog-box {
  width: 100%;
}
</style>
